package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author suliwei
 * @description
 * @date 2025/5/15 10:19
 */
@Slf4j
@RestController
@RequestMapping("excelThree")
public class ExcelThreeController {

    /* 入参格式
    {
	"registeredList": [
		{
			"serialNumber": "1",
			"companyName": "测试1",
			"registrationAddress": "测试1",
			"businessScope": "测试1",
			"marketEntryDate": "测试1",
			"companyType": "测试1",
			"controllingIndustry": "测试1",
			"totalAssets": "测试1"
		}
	],
	"deregisteredList": [
		{
			"serialNumber": "2",
			"companyName": "测试2",
			"registrationAddress": "测试2",
			"cancelledBusinessScope": "测试2",
			"marketExitDate": "测试2",
			"exitReason": "测试2"
		}
	],
	"businessChangeList": [
		{
			"serialNumber": "3",
			"companyName": "测试3",
			"originalBusinessScope": "测试3",
			"updatedBusinessScope": "测试3",
			"marketEntryDate": "测试3",
			"companyType": "测试3",
			"controllingIndustry": "测试3",
			"totalAssets": "测试3"
		}
	]
}
     */
    @RequestMapping("/excelThree")
    public void exportExcel(@RequestBody ExportData exportData, HttpServletResponse response) throws IOException {

        // 测试数据
//        String a = "{\n" +
//                "  \"registeredList\": [\n" +
//                "    {\n" +
//                "      \"serialNumber\": \"1\",\n" +
//                "      \"companyName\": \"测试1\",\n" +
//                "      \"registrationAddress\": \"测试1\",\n" +
//                "      \"businessScope\": \"测试1\",\n" +
//                "      \"marketEntryDate\": \"测试1\",\n" +
//                "      \"companyType\": \"测试1\",\n" +
//                "      \"controllingIndustry\": \"测试1\",\n" +
//                "      \"totalAssets\": \"测试1\"\n" +
//                "    }\n" +
//                "  ],\n" +
//                "  \"deregisteredList\": [\n" +
//                "    {\n" +
//                "      \"serialNumber\": \"2\",\n" +
//                "      \"companyName\": \"测试2\",\n" +
//                "      \"registrationAddress\": \"测试2\",\n" +
//                "      \"cancelledBusinessScope\": \"测试2\",\n" +
//                "      \"marketExitDate\": \"测试2\",\n" +
//                "      \"exitReason\": \"测试2\"\n" +
//                "    }\n" +
//                "  ],\n" +
//                "  \"businessChangeList\": [\n" +
//                "    {\n" +
//                "      \"serialNumber\": \"3\",\n" +
//                "      \"companyName\": \"测试3\",\n" +
//                "      \"originalBusinessScope\": \"测试3\",\n" +
//                "      \"updatedBusinessScope\": \"测试3\",\n" +
//                "      \"marketEntryDate\": \"测试3\",\n" +
//                "      \"companyType\": \"测试3\",\n" +
//                "      \"controllingIndustry\": \"测试3\",\n" +
//                "      \"totalAssets\": \"测试3\"\n" +
//                "    }\n" +
//                "  ]\n" +
//                "}";
//        ExportData data = JSONObject.parseObject(a, ExportData.class);


        try (Workbook workbook = new XSSFWorkbook()) {
            // 注册生效Sheet
            if(CollectionUtils.isNotEmpty(exportData.getRegisteredList())){
                createRegisteredSheet(workbook, exportData.getRegisteredList());
            }
            // 注销生效Sheet
            if(CollectionUtils.isNotEmpty(exportData.getDeregisteredList())) {
                createDeregisteredSheet(workbook, exportData.getDeregisteredList());
            }
            // 业务范围变更Sheet
            if(CollectionUtils.isNotEmpty(exportData.getBusinessChangeList())) {
                createBusinessChangeSheet(workbook, exportData.getBusinessChangeList());
            }

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=export.xlsx");
            workbook.write(response.getOutputStream());
        }
    }

    // 注册生效Sheet生成
    private void createRegisteredSheet(Workbook workbook, List<RegisteredCompany> dataList) {
        Sheet sheet = workbook.createSheet("注册生效统计情况");
        String[] headers = {"序号", "企业名称", "注册地", "业务范围", "入市日期", "售电公司类型", "控股方所属行业", "资产总额（万元）"};
        createHeaderRow(sheet, headers);

        int rowNum = 1;
        for (RegisteredCompany company : dataList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(company.getSerialNumber());
            row.createCell(1).setCellValue(company.getCompanyName());
            row.createCell(2).setCellValue(company.getRegistrationAddress());
            row.createCell(3).setCellValue(company.getBusinessScope());
            row.createCell(4).setCellValue(company.getMarketEntryDate());
            row.createCell(5).setCellValue(company.getCompanyType());
            row.createCell(6).setCellValue(company.getControllingIndustry());
            row.createCell(7).setCellValue(company.getTotalAssets());
        }
        autoSizeColumns(sheet, headers.length);
    }

    // 注销生效Sheet生成
    private void createDeregisteredSheet(Workbook workbook, List<DeregisteredCompany> dataList) {
        Sheet sheet = workbook.createSheet("注销生效统计情况");
        String[] headers = {"序号", "企业名称", "注册地", "注销业务范围", "通市日期", "通市原因"};
        createHeaderRow(sheet, headers);

        int rowNum = 1;
        for (DeregisteredCompany company : dataList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(company.getSerialNumber());
            row.createCell(1).setCellValue(company.getCompanyName());
            row.createCell(2).setCellValue(company.getRegistrationAddress());
            row.createCell(3).setCellValue(company.getCancelledBusinessScope());
            row.createCell(4).setCellValue(company.getMarketExitDate());
            row.createCell(5).setCellValue(company.getExitReason());
        }
        autoSizeColumns(sheet, headers.length);
    }

    // 业务范围变更Sheet生成
    private void createBusinessChangeSheet(Workbook workbook, List<BusinessChangeCompany> dataList) {
        Sheet sheet = workbook.createSheet("售电公司业务范围变更统计情况");
        String[] headers = {"序号", "企业名称", "原业务范围", "变更后业务范围", "入市日期", "售电公司类型", "控股方所属行业", "资产总额（万元）"};
        createHeaderRow(sheet, headers);

        int rowNum = 1;
        for (BusinessChangeCompany company : dataList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(company.getSerialNumber());
            row.createCell(1).setCellValue(company.getCompanyName());
            row.createCell(2).setCellValue(company.getOriginalBusinessScope());
            row.createCell(3).setCellValue(company.getUpdatedBusinessScope());
            row.createCell(4).setCellValue(company.getMarketEntryDate());
            row.createCell(5).setCellValue(company.getCompanyType());
            row.createCell(6).setCellValue(company.getControllingIndustry());
            row.createCell(7).setCellValue(company.getTotalAssets());
        }
        autoSizeColumns(sheet, headers.length);
    }

    // 创建表头通用方法
    private void createHeaderRow(Sheet sheet, String[] headers) {
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }
    }

    // 自动调整列宽
    private void autoSizeColumns(Sheet sheet, int columnCount) {
        for (int i = 0; i < columnCount; i++) {
            sheet.autoSizeColumn(i);
        }
    }

    @Data
    // 数据模型定义
    public static class ExportData {
        private List<RegisteredCompany> registeredList;
        private List<DeregisteredCompany> deregisteredList;
        private List<BusinessChangeCompany> businessChangeList;
    }

    @Data
    public static class RegisteredCompany {
        private String serialNumber;
        private String companyName;
        private String registrationAddress;
        private String businessScope;
        private String marketEntryDate;
        private String companyType;
        private String controllingIndustry;
        private String totalAssets;
    }

    @Data
    public static class DeregisteredCompany {
        private String serialNumber;
        private String companyName;
        private String registrationAddress;
        private String cancelledBusinessScope;
        private String marketExitDate;
        private String exitReason;
    }

    @Data
    public static class BusinessChangeCompany {
        private String serialNumber;
        private String companyName;
        private String originalBusinessScope;
        private String updatedBusinessScope;
        private String marketEntryDate;
        private String companyType;
        private String controllingIndustry;
        private String totalAssets;
    }
}
